<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="勋章id" v-if="dataForm.id">
      {{dataForm.id}}
    </el-form-item>
    <el-form-item label="勋章分类" prop="medalType">
      <el-select v-model="dataForm.medalType">
          <el-option
            v-for="item in medalTypeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="勋章名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="勋章名称(不超过10个字符)" :maxlength="10" style="width:300px"></el-input>
    </el-form-item>
    <!-- <el-form-item label="勋章图标(已获得)" prop="iconGained">
      <el-input v-model="dataForm.iconGained" placeholder="勋章图标-获取状态"></el-input>
    </el-form-item> -->
    <!-- <el-form-item label="勋章图标-未获取状态" prop="iconUngained">
      <el-input v-model="dataForm.iconUngained" placeholder="勋章图标-未获取状态"></el-input>
    </el-form-item> -->
    <!-- <el-form-item label="勋章图标(放大)" prop="iconZoom">
      <el-input v-model="dataForm.iconZoom" placeholder="勋章-放大状态"></el-input>
    </el-form-item>
    <el-form-item label="勋章音效" prop="audio">
      <el-input v-model="dataForm.audio" placeholder="勋章音效"></el-input>
    </el-form-item> -->
    <div class="item-wrapper" style="display: flex;flex-direction: row;margin-top: 30px;justify-content: space-around;margin-left: -40px;">
      <el-form-item prop="iconGained">
        <div class="item-pic-wrapper">
          <span style="color: #f56c6c;margin-right: 4px">*</span>勋章小图标(已获得)：
          <div class="coverImg-wrapper">

            <el-upload ref="uploadCoverImg"
                       :action="uploadCoverImgUrl"
                       :before-upload="beforeCoverImgUpload"
                       :on-error="handleCoverImgError"
                       :on-success="handleCoverImgSuccess"
                       :show-file-list="showCoverImgUpload">
              <img v-if="dataForm.iconGained" class="coverImg" :src="dataForm.iconGained">
              <i v-else class="el-icon-plus coverImg-uploader-icon"></i>
            </el-upload>
          </div>
          <span class="error-tip">{{coverImgErrorTip}}</span>
        </div>
      </el-form-item>
      <el-form-item prop="iconUngained">
        <div class="item-pic-wrapper">
          <span>勋章小图标(未获得)：</span>
          <div class="bannerImg-wrapper pic">
            <el-upload ref="uploadIconImg"
                       :action="uploadIconImgUrl"
                       :before-upload="beforeIconImgUpload"
                       :on-error="handleIconImgError"
                       :on-success="handleIconImgSuccess"
                       :show-file-list="showIconImgUpload">
              <img v-if="dataForm.iconUngained" class="bannerImg" :src="dataForm.iconUngained">
              <i v-else class="el-icon-plus bannerImg-uploader-icon"></i>
            </el-upload>
          </div>
          <span class="error-tip">{{iconImgErrorTip}}</span>
        </div>
      </el-form-item>
      <!-- <el-form-item prop="iconZoom">
        <div class="item-pic-wrapper">
          <span>勋章大图标(已获得)：</span>
          <div class="bannerImg-wrapper pic">
            <el-upload ref="uploadBannerImg"
                       :action="uploadBannerImgUrl"
                       :before-upload="beforeBannerImgUpload"
                       :on-error="handleBannerImgError"
                       :on-success="handleBannerImgSuccess"
                       :show-file-list="showBannerImgUpload">
              <img v-if="dataForm.iconZoom" class="bannerImg" :src="dataForm.iconZoom">
              <i v-else class="el-icon-plus bannerImg-uploader-icon"></i>
            </el-upload>
          </div>
          <span class="error-tip">{{bannerImgErrorTip}}</span>
        </div>
      </el-form-item> -->
      </div>
    <el-form-item label="勋章描述(已获得)" prop="replyComp">
      <el-input v-model="dataForm.replyComp" placeholder="请填写描述(不超过35个字符)" :maxlength="35" style="width:550px"></el-input>
    </el-form-item>
    <el-form-item label="勋章描述(未获得)" prop="replyIncomp">
      <el-input v-model="dataForm.replyIncomp" placeholder="请填写描述(不超过35个字符)" :maxlength="35" style="width:550px"></el-input>
    </el-form-item>
      <el-form-item label="勋章音效(已获得)"
                    prop="audio"
                    style="width: 100%;margin-bottom: 30px;">
        <div style="display: flex;margin-bottom: 10px;">
          <el-tooltip effect="dark"
                      placement="top-start"
                      :content="dataForm.audio ? dataForm.audio : '请先上传音频文件'">
            <el-input disabled
                      v-model="dataForm.audio" placeholder="音频文件的url"></el-input>
          </el-tooltip>
          <el-upload accept=".mp3"
                     action=""
                     :before-upload="beforeUploadMp3"
                     :http-request="fnUploadRequest"
                     :on-error="handleUploadError"
                     :on-success="handleMp3Success"
                     :show-file-list="false">
            <el-button style="margin-left: 10px;"
                       type="primary">上传音频
            </el-button>
          </el-upload>
        </div>
        <el-progress v-if="progress > 0" :percentage="progress"></el-progress>
      </el-form-item>
      <el-form-item label="勋章音效(未获得)"
                    prop="audioUn"
                    style="width: 100%;margin-bottom: 30px;">
        <div style="display: flex;margin-bottom: 10px;">
          <el-tooltip effect="dark"
                      placement="top-start"
                      :content="dataForm.audioUn ? dataForm.audioUn : '请先上传音频文件'">
            <el-input disabled
                      v-model="dataForm.audioUn" placeholder="音频文件的url"></el-input>
          </el-tooltip>
          <el-upload accept=".mp3"
                     action=""
                     :before-upload="beforeUploadMp3"
                     :http-request="fnUploadRequest2"
                     :on-error="handleUploadError"
                     :on-success="handleMp3Success2"
                     :show-file-list="false">
            <el-button style="margin-left: 10px;"
                       type="primary">上传音频
            </el-button>
          </el-upload>
        </div>
        <el-progress v-if="progress2 > 0" :percentage="progress2"></el-progress>
      </el-form-item>
      <el-form-item label="发放条件" prop="type">
        <template>
          <el-radio-group v-model="type" class="radiogroup">
            <el-radio :label="item.type" @change="itemType" v-for="item in listRule" :key="item.type" class="radio">{{item.str1}} {{item.str2}}
             <el-input @change="selectTotal" v-model="item.total"  style="width: 80px" :disabled="type !==item.type" type="number" onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))" min="1"></el-input>
              {{item.str3}}发放</el-radio>
          </el-radio-group>
        </template>
      </el-form-item>
    <!-- <el-form-item label="上下架" prop="status">
      <el-input v-model="dataForm.status" placeholder="上下架"></el-input>
    </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import oss from '../../../utils/aliOss'
  export default {
    data () {
      return {
        coverImgErrorTip: '',
        showCoverImgUpload: true,
        bannerImgErrorTip: '',
        showBannerImgUpload: true,
        iconImgErrorTip: '',
        showIconImgUpload: true,
        progress: 0,
        progress2: 0,
        uploadCoverImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadBannerImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        uploadIconImgUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        visible: false,
        dataForm: {
          name: '',
          medalType: '',
          iconGained: '',
          iconUngained: '',
          iconZoom: '',
          audio: '',
          status: '',
          remark: '',
          type: '',
          total: '',
          audioUn: ''
        },
        type: '',
        medalTypeOptions: [],
        listRule: [],
        dataRule: {
          name: [
            { required: true, message: '勋章名称不能为空', trigger: 'blur' }
          ],
          medalType: [
            { required: true, message: '勋章类型不能为空', trigger: 'blur' }
          ],
          iconGained: [
            { required: true, message: '勋章小图标不能为空', trigger: 'blur' }
          ],
          iconUngained: [
            { required: true, message: '勋章小图标不能为空', trigger: 'blur' }
          ],
          // iconZoom: [
          //   { required: true, message: '勋章大图标不能为空', trigger: 'blur' }
          // ],
          audio: [
            { required: true, message: '勋章音效不能为空', trigger: 'blur' }
          ],
          audioUn: [
            { required: true, message: '勋章音效不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '上下架不能为空', trigger: 'blur' }
          ],
          replyComp: [
            { required: true, message: '描述不能为空', trigger: 'blur' }
          ],
          replyIncomp: [
            { required: true, message: '描述不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        const that = this
        that.dataForm.id = id || 0
        that.visible = true
        that.type = ''
        that.dataForm.total = ''
        that.progress = 0
        that.progress2 = 0
        that.$nextTick(() => {
          that.$refs['dataForm'].resetFields()
          if (that.dataForm.id) {
            that.$http({
              url: that.$http.adornUrl(`/picbook/pbmedal/info/${that.dataForm.id}`),
              method: 'get',
              params: that.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                that.dataForm = data.data.pbMedal
                that.type = data.data.rules[0].type
                that.dataForm.type = that.type
                that.dataForm.total = data.data.rules[0].total
                that.listRule.forEach((value, index) => {
                  if (that.type == value.type) {
                    that.listRule[index].total = that.dataForm.total
                  }
                })
              }
            })
          }
        })
        this.getMedalType()
        this.getRule()
      },
      // 切换单选时置空
      itemType (type) {
        this.dataForm.type = type
        this.dataForm.total = ''
        this.listRule.forEach((value,index) => {
          value.total = ''
        })
      },
      // 输入框取整
      selectTotal (value) {
        this.dataForm.total = Math.round(value)
      },
      // 获取勋章分类
      getMedalType () {
        this.$http({
          url: this.$http.adornUrl(`/picbook/combobox/listMedalType`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.medalTypeOptions = data.data
          }
        })
      },
      // 获取发放条件列表
      getRule () {
        const that = this
        that.$http({
          url: that.$http.adornUrl(`/picbook/pbmedal/listRule`),
          method: 'post',
          params: that.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            that.listRule = data.data
            // 初始化input的值
            that.listRule.forEach(function (value, index) {
              value.total = ''
            })
          }
        })
      },
      handleCoverImgSuccess (res, file) {
        // this.dataForm.coverImg = URL.createObjectURL(file.raw)
        this.dataForm.iconGained = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadCoverImg.clearFiles()
        }, 1000)
      },
      beforeCoverImgUpload (file) {
        this.coverImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.coverImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleCoverImgError (err, file, fileList) {
        this.coverImgErrorTip = '上传失败'
      },
      handleBannerImgSuccess (res, file) {
        // this.dataForm.bannerImg = URL.createObjectURL(file.raw)
        this.dataForm.iconZoom = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadBannerImg.clearFiles()
        }, 1000)
      },
      beforeBannerImgUpload (file) {
        this.bannerImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.bannerImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleBannerImgError (err, file, fileList) {
        this.bannerImgErrorTip = '上传失败'
      },
      handleIconImgSuccess (res, file) {
        // this.dataForm.bannerImg = URL.createObjectURL(file.raw)
        this.dataForm.iconUngained = res.url
        let _this = this
        setTimeout(function () {
          _this.$refs.uploadIconImg.clearFiles()
        }, 1000)
      },
      beforeIconImgUpload (file) {
        this.iconImgErrorTip = ''
        if (file.type.indexOf('image') < 0) {
          this.bannerImgErrorTip = '图片格式不正确'
          return false
        }
      },
      handleIconImgError (err, file, fileList) {
        this.iconImgErrorTip = '上传失败'
      },
      previewPicBook () {
        let _this = this
        _this.$emit('previewPicBook', _this.dataForm)
      },
      uploadProgress (p) {
        this.progress = Math.floor(p * 100)
      },
      uploadProgress2 (p) {
        this.progress2 = Math.floor(p * 100)
      },
      /**
       * @description [fnUploadRequest 覆盖默认的上传行为，实现自定义上传]
       * @param    {object}   option [上传选项]
       * @return   {null}   [没有返回]
       */
      async fnUploadRequest (option) {
        oss.ossUploadFile(option, this.uploadProgress)
      },
      // 上传音乐(未获得)
      /**
       * @description [fnUploadRequest 覆盖默认的上传行为，实现自定义上传]
       * @param    {object}   option [上传选项]
       * @return   {null}   [没有返回]
       */
      // 修改进度条
      async fnUploadRequest2 (option) {
        oss.ossUploadFile(option, this.uploadProgress2)
      },
      // apk上传之前
      beforeUploadMp3 (file) {
        // if (file.type.indexOf('application/vnd.android.package-archive') < 0) {
        //   this.$message.error('apk格式不正确')
        //   return false
        // }
        let name = file.name
        // 字符串截取为了兼容火狐，火狐浏览器获取apk文件的type为空
        var mp3 = name.substring(name.length - 3, name.length)
        const isMp3 = mp3 === 'mp3'
        if (!isMp3) {
          this.$message.error('上传只能是 mp3 格式的音频文件!')
        }
        return isMp3
      },
      // 添加多个文件事件
      beyondFile (files, fileList) {
        this.$message({
          message: '一次只能上传一个mp3文件，请删除重新上传',
          type: 'success'
        })
      },
      // 上传mp3文件
      handleMp3Success (response, file, fileList) {
        if (response == null) {
          return
        }
        let retUrl = response.res.requestUrls[0].split('?')[0]
        if (retUrl) {
          if (window.SITE_CONFIG['baseUrl'] == 'https://xxx-app-api.xxx.cn') {
            this.dataForm.audio = retUrl.replace('https://xxx-edu-epxxx.oss-cn-hangzhou.aliyuncs.com', 'http://huiben-oss-cdn.xxx.cn')
          } else {
            this.dataForm.audio = retUrl
          }
          this.$message.success('上传成功')
        }
      },
      // 上传mp3文件(未获得)
      handleMp3Success2 (response, file, fileList) {
        if (response == null) {
          return
        }
        let retUrl = response.res.requestUrls[0].split('?')[0]
        if (retUrl) {
          if (window.SITE_CONFIG['baseUrl'] == 'https://xxx-app-api.xxx.cn') {
            this.dataForm.audioUn = retUrl.replace('https://xxx-edu-epxxx.oss-cn-hangzhou.aliyuncs.com', 'http://huiben-oss-cdn.xxx.cn')
          } else {
            this.dataForm.audioUn = retUrl
          }
          this.$message.success('上传成功')
        }
      },
      // 上传失败
      handleUploadError (err, file, fileList) {
        this.$message.error('上传失败')
      },
      // 表单提交
      dataFormSubmit () {
        console.log(this.dataForm)
        if (!this.dataForm.total) {
          this.$message('请输入发放条件的具体内容')
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/picbook/pbmedal/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                pbMedal: this.dataForm,
                rules:[{
                  'type': this.dataForm.type,
                  'total': this.dataForm.total
                }]
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  // duration: 1500,
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style scoped lang="less">
  .item-wrapper {
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;
    width: 100%;
    .price-item-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;
      .el-form-item__content {
        float: left;
      }
      .price-input {
        width: 120px;
        margin-left: 10px;
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
        -webkit-appearance: none;
        border: 1px solid #dcdfe6;
        color: #606266;
        padding: 0 15px;
      }
    }
    .item-pic-wrapper {
      display: inline-block;
      .pic {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 20px;
      }
      .avatar-uploader .el-upload {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .coverImg-wrapper {
        .coverImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 150px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .coverImg {
          width: 150px;
          height: 150px;
          display: block;
        }
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
      .bannerImg-wrapper {
        .bannerImg-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          border: 1px solid #d9d9d9;
          border-radius: 6px;
          width: 150px;
          height: 150px;
          line-height: 150px;
          text-align: center;
        }
        .bannerImg {
          width: 150px;
          height: 150px;
          display: block;
        }
      }
    }
  }
  .radio {
    margin-left: 0px;
    margin-top: 10px;
  }
  .radiogroup {
    display: flex;
    flex-flow: column;
  }
</style>